package com.lzc.springPart.aop.advisor;

import java.util.ArrayList;
import java.util.List;

/**
 * 模拟通知类执行流程
 */
public class MockAdvice {

    public static void main(String[] args) {

        List<Advice> list = new ArrayList<>();
        // 创建通知
        Advice advice1 = new Advice() {
            @Override
            public Object invoke(Invocation invocation) {
                System.out.println("before1");
                Object obj = invocation.process();
                System.out.println("After1");
                return obj;
            }
        };
        Advice advice2 = new Advice() {
            @Override
            public Object invoke(Invocation invocation) {
                System.out.println("before2");
                Object obj = invocation.process();
                System.out.println("After2");
                return obj;
            }
        };

        /**------------------------调用cglib的intercept方法--------------------------------**/
        list.add(advice1);
        list.add(advice2);
        // 创建调用器对象
        Invocation invocation = new Invocation(list);
        invocation.process();

    }


    // 通知
    interface Advice{
        public Object invoke(Invocation invocation);
    }


    // 调用器
    static class Invocation{
        private List<Advice> advise = new ArrayList<>();
        private int index = 0;

        public Invocation(List<Advice> advise){
            this.advise = advise;
        }

        public Object process(){
            // 判断集合还有没有没被调用的通知
            if (index == advise.size()){
                System.out.println("原始方法");
                return null;
            }else{
               return advise.get(index++).invoke(this);
            }
        }
    }
}
